<?php
/**
 * Created by PhpStorm.
 * User: Dalei
 * Date: 2018/10/17
 * Time: 14:41
 */

namespace Home\Controller;
use OT\DataDictionary;

class HomepageController extends HomeController{
    /*
     * 轮播图
     * @ picture 图表
     * @ resu 返还数据
     * */
    public function slideshow(){
        $resu = array('code' => 1,'msg' => '轮播图调取成功!','data' => array());
        $data = M('picture')->field('path')->select();
        foreach ($data as $k => $value){
            $data[$k]['path'] = "http://".$_SERVER['HTTP_HOST'].implode($value);
        }
        $resu['data'] = $data;
        $this -> ajaxReturn($resu);
    }
    /*
     *余额
     *
     * @ HTTP_TOKEN 缓存中的token
     * @ personal 个人信息表
     * @ resu 返还数据
     * */
    public function balance(){
        $resu = array('code' => 1,'msg' => '余额值查询成功!','data' => array());
        $tokk = $_SERVER['HTTP_TOKEN'];
        $toke = json_decode(base64_decode($tokk),true);//解密token
        $mobile = $toke['mobile'];//赋值
        $where = array('mobile' => $mobile);
        $data = M('personal')->where($where)->field('balance')->find();
        $dd = implode($data);
        if($data){
            $resu['msg'] = '余额值查询成功!余额为:'.$dd;
            $resu['data'] = $data;
        }else{
            $resu['code'] = 2;
            $resu['msg'] = '余额值查询失败!请先登录';
        }
        $this -> ajaxReturn($resu);
    }

    /*
     *积分
     *
     * @ HTTP_TOKEN 缓存中的token
     * @ personal 个人信息表
     * @ resu 返还数据
     * */
    public function integral(){
        $resu = array('code' => 1,'msg' => '积分值查询成功!','data' => array());
        $tokk = $_SERVER['HTTP_TOKEN'];
        $toke = json_decode(base64_decode($tokk),true);//解密token
        $mobile = $toke['mobile'];//赋值
        $where = array('mobile' => $mobile);
        $data = M('personal')->where($where)->field('integral')->find();
        $dd = implode($data);
        if($data){
            $resu['msg'] = '积分值查询成功!余额为:'.$dd;
            $resu['data'] = $data;
        }else{
            $resu['code'] = 2;
            $resu['msg'] = '积分值查询失败!请先登录';
        }
        $this -> ajaxReturn($resu);
    }
	/*
     * 个人积分明细
     * */
    /*
         * 个人积分明细
         * */
    public function integranl_detail (){
        $resu = array('code' => 1,'msg' => '积分明细查询成功!','data' => array());
        $tokk = $_SERVER['HTTP_TOKEN'];
        $toke = json_decode(base64_decode($tokk),true);//解密token
        $mobile = $toke['mobile'];//赋值
        $list = M('personal') -> where(array('mobile' => $mobile))->field('username')->find();
        $data = M('integral_log')
            ->where(array('username' => $list['username']))
            ->field('integral_from,update_time,username,integral_of')
            ->order('update_time desc')
            ->select();
        foreach($data as $key => $v){
            $data[$key]['update_time'] = date('Y-m-d H:i:s',$v['update_time']);
        }
        if($list){
            $resu['data'] = $data;
        }else{
            $resu['code'] = 2;
            $resu['msg'] = '个人积分明细查询成功';
        }
        $this -> ajaxReturn($resu);
    }
    /*
     * 余额转换为积分
     * @ mobile 从token中获取的电话号码
     * @ personal 个人信息表
     * @ params float balance 余额
     * @ return resu 返还数据
     * */
    public function balance_into_i(){
        $resu = array('code' => 1,'msg' => '余额转换积分成功!','data' => array());
        $tokk = $_SERVER['HTTP_TOKEN'];
        $toke = json_decode(base64_decode($tokk),true);//解密token
        $mobile = $toke['mobile'];//赋值\
        $where = array('mobile' => $mobile);
        $log = $this->balance_log();
        $integral_log = $this -> integral_log();
        $balance = $_POST['balance'];//输入金额
        $data_ba = M('personal')->where($where)->field('balance')->find();
        $data_in = M('personal')->where($where)->field('integral')->find();
		if(empty($mobile) && empty($balance) && empty($data_ba)){
			$resu['code'] = 2;
			$resu['msg'] = '请输入需要转为积分的金额!';
		}else{

			if($data_ba['balance'] > 0){
				if($balance > 0){
					if($data_ba['balance'] > $balance){
						$dat = $balance * C('YUE_INTO_JIFEN') + $data_in['integral'];
						$array = array('integral' => $dat);
						$save = M('personal')->where($where)->save($array);
						if($save){
							$succes = $data_ba['balance'] - $balance;
							$arr = array('balance' => $succes);
							M('personal')->where($where)->save($arr);
							if($log = true && $integral_log = true){

							}
						}
					}else{
						$resu['code'] = 2;
						$resu['msg'] = '已超出余额最大数!';
					}
				}else{
					$resu['code'] = 2;
					$resu['msg'] = '请输入金额!';
				}
				
			}else{
				$resu['code'] = 2;
				$resu['msg'] = '您的余额不足!';
			}
		}
        $this -> ajaxReturn($resu);
    }

    /**
     * 获取积分等级
     * @ int 积分数量
     */
    private function getLevel($int){
        if($int <= 0.01) return false;// 不更新
        if($int < C('QUJIAN_ONE')) return C('SHIFANG_ONE');
        if($int < C('QUJIAN_TWO')) return C('SHIFANG_TWO');
        if($int < C('QUJIAN_THREE')) return C('SHIFANG_THREE');
        if($int < C('QUJIAN_FOUR')) return C('SHIFANG_FOUR');
        if($int >= C('QUJIAN_FOUR')) return C('SHIFANG_FIVE');
    }
    /**
     * 添加释放余额记录
     */
    private function addBalanceLog($data){
        // 更新余额数据到数据表
        $result = M('personal')->where(array('id'=>$data['id']))->setInc('balance',$data['money']);
        // 插入余额变化记录
        if($result){
            $array = array(
                'user_id' => $data['id'],
                'balance' => $data['balance'],
                'balance_v' => $data['balance'] + $data['money'],
                'update_time' => time(),
                'balance_from' => '后台管理员',
                'balance_of'   => $data['money'],
                'username'     => $data['username']
            );
            M('balance_log')->add($array);
        }
    }

    /**
     * 添加释放积分记录
     */
    private function addIntegralLog($data){
        // 更新积分数据到数据表
        $result = M('personal')->where(array('id'=>$data['id']))->setDec('integral',$data['int']);
        // 插入积分变化记录
        if($result){
            $array = array(
                'user_id' => $data['id'],
                'integral' => $data['integral'],
                'integral_v' => $data['integral_after'],
                'update_time' => time(),
                'integral_from' => '后台管理员',
                'integral_of'   => $data['int'],
                'username'     => $data['username']
            );
            M('integral_log')->add($array);
        }
    }

    /*
     * 理财积分
     * @ HTTP_TOKEN 缓存中的token,用于调取当前用户的电话号码
     * @ personal 个人用户信息表
     * @ params float integral 个人积分
     * @ C c方法用于调取后台配置的区间比列以及释放百分比
     * @ resu 返还数据
     * */
    public function integration(){
        $resu = array('code' => 1,'msg' => '积分转换为余额成功!','data' => array());

        // 查询符合条件的数据
        $map['qualification'] = array('neq',B);
        $map['integral'] = array('gt',0); // 自身积分必须大于0
        $data = M('personal')->where($map)->getField('mobile,id,username,integral,balance,superior');//所有用户的电话
        // 获取上下级关系tree
        $array = array();
        foreach($data as $mobile => $val){
            $array[$mobile] = $val;
            foreach($data as $k => $v){
                if($v['superior'] == $mobile){
                    $array[$mobile]['child'][] = $v['integral'];
                }
            }
        }
        // 释放data占用内存
        unset($data);
        //判断是否有下级用户，没有下级的用户就卸载掉,否则就计算出下级总积分、等级、兑换金额、兑换积分,并更新到数据库和写入日志
        foreach($array as $key => $val){
            if(count($val['child']) == 0){
                unset($array[$key]);
            } else {
                $total = 0;
                $total = array_sum($val['child']); // 总积分
                $val['total'] = $total;
                $val['level'] = $this->getLevel($total); // 兑换等级
                if($val['level']){ // 如果有积分兑换比例就执行,否则卸载
                    $integral = 0;
                    $integral = intval($val['integral']);// 用户积分取整
                    $val['int'] = $integral;
                    $val['integral_after'] = ($val['integral']*1000 - $integral*1000)/1000; // 剩余积分
                    $val['money'] = $integral * $val['level'] / C('YUE_INTO_JIFEN'); // 兑换的金额
                    $this->addBalanceLog($val); // 更新用户金额变化
                    $this->addIntegralLog($val); // 更新用户积分变化
                }
                unset($array[$key]); // 卸载信息信息占用内存资源
            }
        }
        $this->ajaxReturn($resu);
    }
    /*
     * 转出余额转换为他人积分
     * @ params string mobile 转出的电话号码
     * @ params string mobile_to 转入的电话号码
     * @ params string balance 转出的余额
     * @ params personal 个人信息表
     * @ return resu 返还数据
     * */
    public function roll_out(){
        $resu = array('code' => 1,'msg' => '余额转换积分成功!','data' => array());
        $tokk = $_SERVER['HTTP_TOKEN'];
        $toke = json_decode(base64_decode($tokk),true);//解密token
        $mobile = $toke['mobile'];//赋值
        $mobile_to = $_POST['mobile_out'];

        $balance = $_POST['balance'];
        $where = array('mobile' => $mobile);
        $datas = M('personal')->where($where)->field('integral')->find();//查询自己账户积分
        $data = implode(M('personal')->where($where)->field('balance')->find());//查询转出账户余额
        $data_mobile_to = M('personal')->where(array('mobile' => $mobile_to))->find();//查询转出账户余额
        if(empty($mobile_to)){
            $resu['code'] = 2;
            $resu['msg'] = '请输入对方的账号!';
        }else{
            if(empty($data_mobile_to)){
                $resu['code'] = 2;
                $resu['msg'] = '对方还未注册,转入失败!';
            }else{
                if($balance && $balance > 0){
                    if(empty($data)){
                        $resu['code'] = 2;
                        $resu['msg'] = '您的余额不足!';
                    }else{
                        if($mobile == $mobile_to){
                            $resu['code'] = 2;
                            $resu['msg'] = '转入的账户不能是自己!';
                        }else{
                            if($data >= $balance){
                                $integral = $balance * C('YUE_INTO_JIFEN');
                                $data_to = implode(M('personal')->where(array('mobile' => $mobile_to))->field('integral')->find());
                                $integral_to = $integral + $data_to;
                                $arr = array('integral' => $integral_to);
                                $save = M('personal')->where(array('mobile' => $mobile_to))->save($arr);//储存积分
                                /*@小翔转出余额兑换自己积分*/
                                if($save){
                                    $balance_out = $data - $balance;
                                    $array = array('balance' => $balance_out);
                                    M('personal')->where($where)->save($array);
                                    $log = $this->balance_log_out();
                                    $integral_log = $this -> integral_log_out();
                                    if($log = true && $integral_log = true){
                                        if ($datas) {
                                            $zhuanc=$balance * C('JIFEN_YH');//兑换积分
                                            $dat = $zhuanc + $datas['integral'];//转出余额兑积分
                                            $arraye=array( 'integral' =>$dat,);//转出前的积分)
                                            M('personal')->where($where)->save($arraye);
                                            $datarr = implode(M('personal')->where($where)->field('username')->find());//查询转出账户名字
                                            $datarra = (M('personal')->where($where)->field('id')->find());//查询转出账户名字
                                            $arrays = array(
                                                'integral' =>$datas['integral'],//转出前的积分
                                                'integral_v' => $dat,//转入后的积分
                                                'integral_of' =>  $zhuanc,//系统配发的积分
                                                'update_time' => time(),//时间
                                                'integral_from' => "系统派发",//操作着
                                                'user_id' => $datarra['id'],//被操作者的id
                                                'username' =>$datarr);//被操作者的名字
                                            M('integral_log')->add($arrays);
                                        }else{
                                            $resu['code'] = 2;
                                            $resu['msg'] = '转入失败,对方还没有注册!';
                                        }
                                    }else{
                                        $resu['code'] = 2;
                                        $resu['msg'] = '日志储存失败!';
                                    }
                                }else {
                                    $resu['code'] = 2;
                                    $resu['msg'] = '日志储存失败!';
                                }
                            }else{
                                $resu['code'] = 2;
                                $resu['msg'] = '转出余额大于所剩余额!';
                            }
                        }

                    }
                }else{
                    $resu['code'] = 2;
                    $resu['msg'] = '请输入金额!';

                }
            }
        }

        $this->ajaxReturn($resu);
    }
    /*
     *解析电话号码,查出该用户下级
     * @params string mobile 加密的电话
     * */
    public function junior (){
        $resu = array('code' => 1,'msg' => '下级用户总数查询成功!','data' => array());
        $mobile = base64_decode($_POST['mobile']);//解析前台传回来的电话号码
        $list = M('personal')->where(array('superior' => $mobile))->count();
        if(empty($list)){
            $resu['code'] = 2;
            $resu['msg'] = '您还没有下级用户!';
        }else{
            $resu['data'] = $list;
        }
        $this -> ajaxReturn($resu);
    }
/*
 * 积分兑换倍数
 * */
    public function multiple (){
            $resu = array('code' => 1,'msg' => '积分值查询成功!','data' => array());
            $data = C('YUE_INTO_JIFEN') ;
            if($data){
                $resu['data'] = $data;
            }
            $this -> ajaxReturn($resu);
    }

}